package com.ruicar.afs.cloud.product.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.uid.AfsSequenceGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.product.condition.ProductDiscountPlanCondition;
import com.ruicar.afs.cloud.product.entity.ProductDiscountPlan;
import com.ruicar.afs.cloud.product.entity.ProductDiscountSubsidy;
import com.ruicar.afs.cloud.product.entity.ProductPlan;
import com.ruicar.afs.cloud.product.enums.ProductOnlineStatus;
import com.ruicar.afs.cloud.product.enums.StatusEnum;
import com.ruicar.afs.cloud.product.enums.StatusType;
import com.ruicar.afs.cloud.product.service.ProductDiscountConfigService;
import com.ruicar.afs.cloud.product.service.ProductDiscountPlanService;
import com.ruicar.afs.cloud.product.service.ProductPlanService;
import com.ruicar.afs.cloud.product.vo.ExtrasInfoVo;
import com.ruicar.afs.cloud.product.vo.ProductDiscountPlanVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yaorui.zhang
 * @date 2020年5月13日11:23:27
 */
@RestController
@AllArgsConstructor
@RequestMapping("/productDiscountPlan")
@Api(value = "productDiscountPlan", description = "产品贴息方案")
public class ProductDiscountPlanController {

    private final ProductDiscountPlanService productDiscountPlanService;
    private final ProductDiscountConfigService productDiscountConfigService;
    private final ProductPlanService productPlanService;
    private final AfsSequenceGenerator afsSequenceGenerator;

    @GetMapping("/info/{id}")
    public IResponse<ProductDiscountPlan> getProductDiscountPlanById(@PathVariable String id) {
        return new IResponse<>(productDiscountPlanService.getProductDiscountPlanById(id));
    }

    @PostMapping(value = "/getProductDiscountPlanListData")
    @ApiOperation(value = "多条件分页获取产品贴息方案")
    public IResponse<IPage<ProductDiscountPlan>> listProductDiscountPlan(@RequestBody QueryCondition<ProductDiscountPlanCondition> plan) {
        Page page = new Page(plan.getPageNumber(), plan.getPageSize());
        IPage<List<ProductDiscountPlanVo>> list = productDiscountPlanService.getListProductDiscountPlan(page, plan.getCondition());
        return IResponse.success(list);
    }

    @PostMapping(value = "/getSelectDiscountShare")
    @ApiOperation(value = "获取贴息方案来源信息")
    public IResponse<IPage<ExtrasInfoVo>> getSelectDiscountShare() {
        List<ExtrasInfoVo> list = productDiscountPlanService.getSelectDiscountShare();
        return IResponse.success(list);
    }

    @Transactional
    @PostMapping(value = "/effectiveDiscountPlan/{ids}")
    @ApiOperation(value = "贴息方案生效操作")
    public IResponse<Boolean> effectiveByIds(@PathVariable List<Long> ids) {
        for (Long id : ids) {
            ProductDiscountPlan plan = productDiscountPlanService.getById(id);
            plan.setStatus(AfsEnumUtil.key(StatusEnum.YES));
            productDiscountPlanService.updateById(plan);
        }
        return new IResponse<Boolean>().setMsg("操作成功");
    }

    @Transactional
    @PostMapping(value = "/invalidDiscountPlan/{ids}")
    @ApiOperation(value = "贴息方案无效操作")
    public IResponse<Boolean> invalidByIds(@PathVariable List<Long> ids) {
        List<ProductPlan> list = productPlanService.list(Wrappers.<ProductPlan>query().lambda()
                .eq(ProductPlan::getStatus, AfsEnumUtil.key(ProductOnlineStatus.GO_ONLINE))
                .in(ProductPlan::getDiscountPlanId, ids)
        );
        if (list.size() > 0) return IResponse.fail("方案被上线产品使用不可设置无效！");
        for (Long id : ids) {
            ProductDiscountPlan plan = productDiscountPlanService.getById(id);
            if (!AfsEnumUtil.key(StatusEnum.NO).equals(plan.getStatus())) {
                plan.setStatus(AfsEnumUtil.key(StatusEnum.NO));
                productDiscountPlanService.updateById(plan);
            }
        }
        return new IResponse<Boolean>().setMsg("操作成功");
    }

    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "通过id删除方案")
    public IResponse<Boolean> deletePlan(@PathVariable String id) {
        ProductDiscountPlan plan = productDiscountPlanService.getById(id);
        if (AfsEnumUtil.key(StatusEnum.YES).equals(plan.getStatus()))
            return new IResponse<Boolean>().setMsg("方案生效不可删除！");
        List<ProductPlan> list = productPlanService.list(Wrappers.<ProductPlan>query().lambda()
                .eq(ProductPlan::getDiscountPlanId, id)
        );
        if (list.size() > 0)
            return IResponse.fail("方案被产品使用不可删除！");
        /**
         * 第一步：删除产补贴方信息
         */
        productDiscountConfigService.remove(Wrappers.<ProductDiscountSubsidy>query().lambda()
                .eq(ProductDiscountSubsidy::getDiscountPlanId, id));
        /**
         * 第二步：删除方案
         */
        productDiscountPlanService.removeById(id);
        return new IResponse<Boolean>().setMsg("删除数据成功!");
    }

    @RequestMapping(value = "/copyPlan", method = RequestMethod.POST)
    @ApiOperation(value = "方案复制")
    public IResponse copyPlan(@RequestBody ProductDiscountPlan plan) {
        //查询是否有相同编号的方案
        ProductDiscountPlan scheme = productDiscountPlanService.getOne(Wrappers.<ProductDiscountPlan>query().lambda()
                        .eq(ProductDiscountPlan::getDiscountPlanName, plan.getDiscountPlanName())
                , false
        );
        if (scheme != null) {
            return IResponse.fail("名称重复，请重新填写方案名称！");
        }
        //获取编号
        Long seqno = afsSequenceGenerator.genNext(AfsEnumUtil.key(StatusType.PRODUCT_NUM_TXFA), StatusType.PRODUCT_NUM_TXFA.toString());
        String planNo = AfsEnumUtil.key(StatusType.PRODUCT_NUM_TXFA) + DateUtil.year(DateUtil.date()) +StringUtils.leftPad(String.valueOf(seqno), 4, '0');// 编号
        plan.setDiscountNo(planNo);
        //原方案ID
        Long oldPlanID = plan.getId();
        //保存方案
        plan.setId(null);
        plan.setStatus(AfsEnumUtil.key(StatusType.INVALID));
        plan.setCreateBy(null);
        plan.setCreateTime(null);
        productDiscountPlanService.save(plan);
        //新方案ID
        Long newPlanID = plan.getId();
        //复制补贴信息
        productDiscountConfigService.copyPlan(oldPlanID, newPlanID);
        return IResponse.success(plan);
    }


}
